package com.dsj.gxrd.modules.activity.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsj.gxrd.modules.activity.domain.entity.RdPeopleLedger;
import com.dsj.gxrd.modules.activity.domain.query.RdPeopleLedgerQuery;
import com.dsj.gxrd.modules.activity.mapper.RdPeopleLedgerMapper;
import com.dsj.gxrd.modules.activity.service.RdPeopleLedgerService;
import com.dsj.gxrd.modules.people.service.RdUserInfoService;
import com.dsj.gxrd.utils.BaseEntityHandlerUtils;
import com.google.common.collect.Lists;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author songpin566
 * @date 2023/10/10
 **/
@Service
public class RdPeopleLedgerServiceImpl extends ServiceImpl<RdPeopleLedgerMapper, RdPeopleLedger> implements RdPeopleLedgerService {

    @Autowired
    private RdPeopleLedgerMapper rdPeopleLedgerMapper;

    @Autowired
    private RdUserInfoService userService;

    @Override
    public List<RdPeopleLedger> selectPeopleLedgerList(RdPeopleLedgerQuery query) {
        List<RdPeopleLedger> rdPeopleLedgers = rdPeopleLedgerMapper.selectPeopleLedgerList(query);
        for (RdPeopleLedger peopleLedger : rdPeopleLedgers) {
            String userId = peopleLedger.getUserId();
            if (StringUtils.isNotEmpty(userId)) {
                Set<Long> collect = Arrays.stream(userId.split(",")).mapToLong(Long::parseLong).boxed().collect(Collectors.toSet());
                List<String> userNames = userService.getUserInfoNamesByIds(collect);
                if (userNames != null) {
                    String join = String.join(",", userNames);
                    peopleLedger.setUserNames(join);
                }
            }
        }
        return rdPeopleLedgers;
    }

    @Override
    public boolean insertPeopleLedger(RdPeopleLedger rdPeopleLedger) {
        BaseEntityHandlerUtils.fastSetBaseEntity(rdPeopleLedger, SecurityUtils.getLoginUser(), false);
        rdPeopleLedger.setDelFlag(0);
        return save(rdPeopleLedger);
    }

    @Override
    public boolean updatePeopleLedger(RdPeopleLedger rdPeopleLedger) {
        BaseEntityHandlerUtils.fastSetBaseEntity(rdPeopleLedger, SecurityUtils.getLoginUser(), true);
        return updateById(rdPeopleLedger);
    }

    @Override
    public AjaxResult removes(List<Long> ids) {
        return removeBatchByIds(ids) ? AjaxResult.success("删除成功") : AjaxResult.error();
    }

}
